<template>
  <view class="next-tree">
    <view class="next-tree-mask" :class="{ show: showTree }" @tap="_cancel"></view>
    <view class="next-tree-cnt" :class="{ show: showTree }">
      <view class="next-tree-bar">
        <view
          class="next-tree-bar-cancel"
          :style="{ color: cancelColor }"
          hover-class="hover-c"
          @tap="_cancel"
          >取消</view
        >
        <view class="next-tree-bar-title" :style="{ color: titleColor }">{{
          title
        }}</view>
        <view
          class="next-tree-bar-confirm"
          :style="{ color: confirmColor }"
          hover-class="hover-c"
          @tap="_confirm"
          >确定</view
        >
      </view>
      <view class="next-tree-view">
        <scroll-view
          class="next-tree-view-sc"
          :scroll-y="true"
          @scrolltolower="scrolltolowerHandler"
        >
          <block v-for="(item, index) in treeList" :key="index">
            <view
              class="next-tree-item"
              :style="[
                {
                  paddingLeft: item.rank * 15 + 'px',
                  zIndex: item.rank * -1 + 50,
                },
              ]"
              :class="{
                border: border === true,
                show: item.show,
                last: item.lastRank,
                showchild: item.showChild,
                open: item.open,
              }"
            >
              <view class="next-tree-label" @tap.stop="_treeItemTap(item, index)">
                <image
                  class="next-tree-icon"
                  :src="
                    item.lastRank ? lastIcon : item.showChild ? currentIcon : defaultIcon
                  "
                ></image>
                {{ item.name }}
              </view>
              <view
                class="next-tree-check"
                @tap.stop="_treeItemSelect(item, index)"
                v-if="selectParent ? true : item.lastRank"
              >
                <view
                  class="next-tree-check-yes"
                  v-if="item.checked"
                  :class="{ radio: !multiple }"
                  :style="{
                    'border-color': confirmColor,
                    'background-color': confirmColor,
                  }"
                >
                  <view
                    class="next-tree-check-yes-b"
                    :style="{ 'background-color': confirmColor }"
                  >
                    <text class="icon-text">✔</text>
                  </view>
                </view>
                <view
                  class="next-tree-check-no"
                  v-else
                  :class="{ radio: !multiple }"
                  :style="{ 'border-color': confirmColor }"
                ></view>
              </view>
            </view>
          </block>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "next-tree",
  props: {
    treeData: {
      type: Array,
      default: function () {
        return [];
      },
    },
    valueKey: {
      type: String,
      default: "id",
    },
    labelKey: {
      type: String,
      default: "label",
    },
    childrenKey: {
      type: String,
      default: "children",
    },
    title: {
      type: String,
      default: "",
    },
    multiple: {
      // 是否可以多选
      type: Boolean,
      default: false,
      // default: true
    },
    selectParent: {
      //是否可以选父级
      type: Boolean,
      default: false,
    },
    checkStrictly: {
      //是否遵循父子不关联
      type: Boolean,
      default: false,
    },
    foldAll: {
      //折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
      type: Boolean,
      default: false,
    },
    confirmColor: {
      // 确定按钮颜色
      type: String,
      default: "#f9ae3d", // #f9ae3d
    },
    cancelColor: {
      // 取消按钮颜色
      type: String,
      default: "", // #757575
    },
    titleColor: {
      // 标题颜色
      type: String,
      default: "", // #757575
    },
    currentIcon: {
      // 展开时候的ic
      type: String,
      default:
        "",
    },
    defaultIcon: {
      // 折叠时候的ic
      type: String,
      default:
        "",
    },
    lastIcon: {
      // 没有子集的ic
      type: String,
      default: "",
    },
    // 是否手动append
    isManuallyAppend: {
      type: Boolean,
      default: false,
    },
    // 默认选择项
    defaultSelectedIds: {
      type: Array,
      default: () => [],
    },
    border: {
      // 是否有分割线
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showTree: false,
      treeList: [],
      selectIndex: -1,
    };
  },
  computed: {},
  methods: {
    _show() {
      this.showTree = true;
    },
    _hide() {
      this.treeList = [];
      this.showTree = false;
    },
    _cancel() {
      this._hide();
      this.$emit("cancel", "");
    },

    // 滚动底部
    scrolltolowerHandler() {
      this.$emit("scrolltolower");
    },

    _confirm() {
      // 处理所选数据
      let rt = [],
        obj = {};
      this.treeList.forEach((v, i) => {
        if (this.treeList[i].checked) {
          obj = {};
          obj.parents = this.treeList[i].parents;
          obj = Object.assign(obj, this.treeList[i].source);
          // 移除子元素
          delete obj.children;
          rt.push(obj);
        }
      });
      this._hide();
      this.$emit("confirm", rt);
    },
    //扁平化树结构
    _renderTreeList(list = [], rank = 0, parentId = [], parents = []) {
      list.forEach((item) => {
        this.treeList.push({
          id: item[this.valueKey],
          name: item[this.labelKey],
          source: item,
          parentId, // 父级id数组
          parents, // 父级id数组
          rank, // 层级
          showChild: false, //子级是否显示
          open: false, //是否打开
          show: rank === 0, // 自身是否显示
          hideArr: [],
          orChecked: item.checked ? item.checked : false,
          checked: item.checked ? item.checked : false,
        });
        if (Array.isArray(item[this.childrenKey]) && item[this.childrenKey].length > 0) {
          let parentid = [...parentId],
            parentArr = [...parents],
            childrenid = [];
          delete parentArr.children;
          parentid.push(item[this.valueKey]);
          parentArr.push({
            [this.valueKey]: item[this.valueKey],
            [this.labelKey]: item[this.labelKey],
            ...item,
          });
          this._renderTreeList(item[this.childrenKey], rank + 1, parentid, parentArr);
        } else {
          this.treeList[this.treeList.length - 1].lastRank = true;
        }
      });
    },
    // 处理默认选择
    _defaultSelect() {
      this.treeList.forEach((v, i) => {
        if (v.checked) {
          this.treeList.forEach((v2, i2) => {
            if (v.parentId.toString().indexOf(v2.parentId.toString()) >= 0) {
              v2.show = true;
              if (v.parentId.includes(v2.id)) {
                v2.showChild = true;
                v2.open = true;
              }
            }
          });
        }
      });
    },
    // 点击
    _treeItemTap(item, index) {
      if (item.lastRank === true) {
        //点击最后一级时触发事件
        this.treeList[index].checked = !this.treeList[index].checked;
        this._fixMultiple(index);
        return;
      }
      let list = this.treeList;
      let id = item.id;
      item.showChild = !item.showChild;
      item.open = item.showChild ? true : !item.open;
      list.forEach((childItem, i) => {
        if (item.showChild === false) {
          //隐藏所有子级
          if (!childItem.parentId.includes(id)) {
            return;
          }
          if (!this.foldAll) {
            if (childItem.lastRank !== true && !childItem.open) {
              childItem.showChild = false;
            }
            // 为隐藏的内容添加一个标记
            if (childItem.show) {
              childItem.hideArr[item.rank] = id;
            }
          } else {
            if (childItem.lastRank !== true) {
              childItem.showChild = false;
            }
          }
          childItem.show = false;
        } else {
          // 打开子集
          if (childItem.parentId[childItem.parentId.length - 1] === id) {
            childItem.show = true;
          }
          // 打开被隐藏的子集
          if (childItem.parentId.includes(id) && !this.foldAll) {
            if (childItem.hideArr[item.rank] === id) {
              childItem.show = true;
              if (childItem.open && childItem.showChild) {
                childItem.showChild = true;
              } else {
                childItem.showChild = false;
              }
              childItem.hideArr[item.rank] = null;
            }
          }
        }
      });
    },
    _treeItemSelect(item, index) {
      this._fixMultiple(item, index);
    },
    // 处理单选多选
    _fixMultiple(item, index) {
      if (!this.multiple) {
        // 如果是单选
        this.treeList.forEach((v, i) => {
          if (i != index) {
            this.treeList[i].checked = false;
          } else {
            this.treeList[i].checked = true;
          }
        });
      } else {
        //如果是多选
				if(item.parentId.length === 0){
					const childs = this.treeList.filter(e=>e.parentId[0] === item.id)
					const childChecked = childs.filter(e=>e.checked)
					if(childChecked.length>0){
						this.treeList[index].checked = true;
						return;
					}
				}
      	this.treeList[index].checked = !this.treeList[index].checked;
        if (this.checkStrictly && item.parentId.length > 0&&this.treeList[index].checked) {

          item.parentId.forEach((res) => {
            const parentItem = this.treeList.find((v) => v.id === res);
            if (parentItem) {
              parentItem.checked = true;
            }
          });
        }
      }
    },
    // 重置数据
    _reTreeList() {
      this.treeList.forEach((v, i) => {
        this.treeList[i].checked = v.orChecked;
      });
    },
    _initTree(treeData = this.treeData) {
      this.treeList = [];
      this._renderTreeList(treeData);
      this.$nextTick(() => {
        this._defaultSelect(treeData);
      });
    },
    // 追加
    appendList(list = []) {
      this._renderTreeList(list);
      this.$nextTick(() => {
        this._defaultSelect(list);
      });
    },
		// 设置选中状态
    checkedTreeData(selectIds) {
      this.treeList.forEach((item) => {
        if (selectIds.indexOf(item.id) !== -1) {
          item.checked = true;
        }
        if (item.children && item.children.length) {
          this.checkedTreeData(item.children, selectIds);
        }
      });
    },
    init() {
      if (this.defaultSelectedIds.length > 0) {
				this.checkedTreeData(this.defaultSelectedIds)
      }
			this.$nextTick(()=>{
				this.showTree = true;
			})
    },
  },
  mounted() {
    if (!this.isManuallyAppend) {
      this._initTree();
      this.$watch(
        () => this.treeData,
        (list) => {
          this._initTree(list);
        },
        { deep: true, immediate: true }
      );
    }
    this.$watch(
      () => [this.multiple, this.selectParent],
      () => {
        if (this.treeData.length) {
          this._reTreeList();
        }
      },
      { deep: true, immediate: true }
    );
  },
};
</script>

<style scoped>
@import "./style.css";
</style>
